package com.itpan.Controller;

import com.itpan.Entity.Employee;
import com.itpan.Entity.EmployeeDto;
import com.itpan.Service.EmailService;
import com.itpan.Service.EmployeeService;
import com.itpan.Utils.ImgUtils;
import com.itpan.Utils.JwtUtils;
import com.itpan.Utils.ValidateCodeUtils;

import com.itpan.common.BaseContext;
import com.itpan.common.CustomException;
import com.itpan.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
@Api(value = "登入注册")
@Slf4j
@RestController
@RequestMapping("/user")
public class RegisterLoginController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private EmailService emailService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ImgUtils imgUtils;

    /*
    发送邮件,并保存在redis中
     */

    @ApiOperation(value = "发送验证码")
    @GetMapping("/sentpin")
    public R<String> senPIN(String Email){
        String PIN = ValidateCodeUtils.generateValidateCode4String(6);
        log.info(PIN);
        emailService.sendEmail(PIN,Email);
        return R.success("验证码发送成功");
    }
@ApiOperation(value = "注册")
    @PostMapping("/register")
    public R<String> register(@ModelAttribute EmployeeDto employeeDto,@RequestParam("file") MultipartFile file){

        //判断验证码是否失效：
        String PIN = (String)redisTemplate.opsForValue().get(employeeDto.getEmployeeEmail());
        if(PIN==null)return R.error("验证码已失效");

        //校对验证码：
        if (!employeeDto.getPin().equals(PIN)) return R.error("验证码错误");


        if(employeeDto.getEmployeeID()==null)
            return R.error("输入的账号为空");

        //1:判断用户根据员工编号查询是否注册过
        Employee em = employeeService.getEmployeeById(employeeDto.getEmployeeID());
        if(em==null){
            //从Dto转到具体实体
            Employee employee = imgUtils.saveImgAndGetEmployee(employeeDto,file);

            //此id没有被注册，可以进行注册流程
            employeeService.saveOne(employee);
//            redisTemplate.opsForValue().decrement(employeeDto.getEmployeeEmail());
            redisTemplate.delete(employeeDto.getEmployeeEmail());
            return R.success("注册成功");
        }
    redisTemplate.delete(employeeDto.getEmployeeEmail());

        return R.error("注册失败，账号已存在");

    }


    @ApiOperation(value = "登入")
    @PostMapping("/login")
    public R<EmployeeDto> Login(@RequestBody EmployeeDto employeeDto){
        //获取缓存验证码
        String PIN = (String)redisTemplate.opsForValue().get(employeeDto.getEmployeeEmail());
        if(PIN==null){
            return R.error("验证码已过期");
        }

        //判断验证码是否一致,成功和失败都要去掉redis里面的记录
        if(!(PIN.equals(employeeDto.getPin()))){
//            redisTemplate.opsForValue().decrement(employeeDto.getEmployeeEmail());
            redisTemplate.delete(employeeDto.getEmployeeEmail());
            return R.error("验证码错误");
        }
//        redisTemplate.opsForValue().decrement(employeeDto.getEmployeeEmail());
        redisTemplate.delete(employeeDto.getEmployeeEmail());


//        Employee em = employeeService.getEmployeeById(employeeDto.getEmployeeID());
        Employee em=employeeService.getemployeebyemail(employeeDto.getEmployeeEmail());
        if(em==null) return R.error("用户不存在");

        //校验密码
        String pas1 = employeeDto.getEmployeePassword();
        String pas2 = em.getEmployeePassword();

        if(!pas1.equals(pas2)) return R.error("密码错误");

        //校验成功，开始后面逻辑

        //存入taken和threadlocal



        HashMap<String,String> map=new HashMap<>();
        map.put("employeeID",em.getEmployeeID().toString());
        map.put("EmployeeName",em.getEmployeeName());

        String token = JwtUtils.getToken(map);
        BaseContext.setCurrentId(em.getEmployeeID());

      //不用存，token已经有时间限制了
//        redisTemplate.opsForValue().set(employeeDto.getEmployeeID(),token);

        EmployeeDto empD=new EmployeeDto();
        BeanUtils.copyProperties(em,empD);
        empD.setToken(token);
//
        return R.success(empD);
    }





}
